package com.northpool.operator.common.groovy;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import com.northpool.operator.IOperatorHandler;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.ParamUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Map;

public class OperatorExecutorImpl {

    public static void main(String[] args) {
        // 第一个参数是算子文件路径
        if(ArrayUtils.isEmpty(args)) {
            throw new RuntimeException("缺少算子源代码参数");
        }
        String workPath = System.getProperty("user.dir");
        String sourcePath = workPath + File.separator + args[0];
        if (!FileUtil.exist(sourcePath)) {
            throw new RuntimeException("未找到源代码路径: " + sourcePath);
        }
        IOperatorHandler originHandler;
        IOperatorHandler execHandler;
        String codeSource = FileUtil.readUtf8String(sourcePath);
        try {
            StopWatch timer = new StopWatch();
            timer.start();
            originHandler = OperatorFactory.getInstance().loadNewInstance(codeSource);
            timer.stop();
            Console.print("编译耗时: {}\n", timer.getTotalTimeMillis());
            execHandler = new OperatorHandler(originHandler);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            Map<String, String> envMap = System.getenv();

            if (StringUtils.isNotEmpty(envMap.get("JM_INSTANCE_NAME"))) {
                ParamTool.Builder builder = new ParamTool.Builder();
                InputParams inputParams = AnnotationUtil.getAnnotation(originHandler.getClass().getConstructors()[0], InputParams.class);
                for (InputParam inputParam : inputParams.value()) {
                    String value = ParamUtils.parse(inputParam.ref());
                    builder.add(inputParam, value);
                }
                execHandler.execute(builder.build());
            } else {
                throw new RuntimeException("非JIANMU流程引擎触发");
            }
        } catch (Throwable e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
